import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  Avatar,
  message,
  Badge,
  Radio,
  Popconfirm,
  Icon,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import AuthorModal from '../../components/Content/AuthorModal';
import { imgPrex } from '../../utils/constData';

import styles from './Author.less';

const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');


@connect(({ author, loading }) => ({
  author,
  authorList: author.authorList,
  pagination: author.pagination,
  loading: loading.models.author,
}))
@Form.create()
export default class Author extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    formValues: {},
    record: null,
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'author/fetchAuthorList',
      payload: { pageNum: 1, pageSize: 10 }
    });
  }

  _setModalVisible(flag, record) {
    if (!flag) {
      if (form) {
        form.resetFields();
      }

      this.setState({
        modalVisible: false,
        record: null,
      });
    } else {
      console.log('模态框打开------', record)
      this.setState({
        modalVisible: true,
        record: record ? record : null,
      });
    }
  }

  handleStandardTableChange = (pagination) => {
    const { dispatch } = this.props;
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...this.props.form.getFieldsValue(),
    };

    if (params.authorSts == '-1') {
      params.authorSts = undefined;
    }

    dispatch({
      type: 'author/fetchAuthorList',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'author/fetchAuthorList',
      payload: { pageNum: 1, pageSize: 10 },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch() {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.authorSts == '-1') {
        fieldsValue.authorSts = undefined;
      }

      const values = {
        ...fieldsValue,
        "pageNum": (this.props.pagination && this.props.pagination.current) ? this.props.pagination.current : 1,
        "pageSize": this.props.pagination.pageSize ? this.props.pagination.pageSize : 10,
      };

      this.setState({
        formValues: values,
      });

      console.log(values)

      dispatch({
        type: 'author/fetchAuthorList',
        payload: values,
      });
    });
  };

  renderSimpleForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="作者姓名">
              {getFieldDecorator('authorName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('authorSts', { initialValue: '-1' })(
                <Select style={{ width: '100%' }}>
                  <Option value="-1">全部</Option>
                  <Option value="0">正常</Option>
                  <Option value="1">冻结</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  _setModalVisible(flag, record) {
    if (!flag) {
      this.setState({
        modalVisible: flag,
        record: null,
        fileList: [],
        file: null,
        image: null,
      });
    } else {
      this.setState({
        modalVisible: true,
        record: record ? record : null,
        image: record ? record.channelImg : null,
      });
    }
  }

  _addAuthor(fieldsValue) {
    if (fieldsValue.authorId) {
      this.props.dispatch({
        type: 'author/updateAuthor',
        payload: fieldsValue,
        callback: () => this._callback()
      })
    } else {
      this.props.dispatch({
        type: 'author/addAuthor',
        payload: fieldsValue,
        callback: () => this._callback()
      })
    }
  }

  _callback() {
    this._setModalVisible(false);
    this.handleSearch();
  }


  _changeAuthorStatus(type) {
    let { selectedRows } = this.state;
    if (selectedRows && selectedRows.length > 0) {
      let recordList = [];
      for (let i in selectedRows) {
        let one = { authorId: selectedRows[i].authorId }
        recordList.push(one)
      }

      if (recordList) {
        this.props.dispatch({
          type: 'author/changeAuthorStatus',
          payload: { authorList: recordList, "authorSts": type },
          callback: () => this._callback()
        });
      }
    } else {
      message.error('请选择内容')
    }
  }

  _delete() {
    let { selectedRows } = this.state;
    if (selectedRows && selectedRows.length > 0) {
      let recordList = [];
      for (let i in selectedRows) {
        let one = { authorId: selectedRows[i].authorId }
        recordList.push(one)
      }

      if (recordList) {
        this.props.dispatch({
          type: 'author/deleteAuthor',
          payload: { authorList: recordList },
          callback: () => this._callback()
        });
      }
    } else {
      message.error('请选择内容')
    }
  }

  render() {
    const {
      authorList,
      pagination,
      loading,
    } = this.props;
    const { selectedRows, modalVisible } = this.state;

    const tableData = {}
    tableData['list'] = authorList;
    tableData['pagination'] = pagination;

    const columns = [
      {
        title: '编号',
        dataIndex: 'authorId',
        key: 'authorId',
      },
      {
        title: '头像',
        dataIndex: 'authorImg',
        key: 'authorImg',
        render(text, record) {
          return <img src={imgPrex + text} alt={record.title} style={{ width: 30, height: 30 }} />;
        },
      },
      {
        title: '姓名',
        dataIndex: 'authorName',
        key: 'authorName',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render(text, record) {
          return <span>{record.authorSts == '0' ? '正常' : record.authorSts == '1' ? '冻结' : '其他'}</span>;
        },
      },
      {
        title: '录入时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '操作',
        render: (record) => (
          <Fragment>
            <a onClick={() => this._setModalVisible(true, record)}>编辑</a>
          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };

    return (
      <PageHeaderLayout title="">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this._setModalVisible(true)}>
                添加
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button type="dashed" icon="close-square" onClick={() => this._changeAuthorStatus(1)}>
                    冻结
                  </Button>
                  <Button type="dashed" icon="check-square" onClick={() => this._changeAuthorStatus(0)}>
                    解冻
                  </Button>
                  <Popconfirm title="确定要删除选中的频道吗?" placement="bottom" onConfirm={() => this._delete()} onCancel={() => { }} okText="确定" cancelText="取消">
                    <Button type="danger" icon="delete" >
                      删除
                  </Button>
                  </Popconfirm>
                </span>
              )}
            </div>

            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={tableData}
              rowKey="authorId"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {/* <CreateForm {...parentMethods} modalVisible={modalVisible} /> */}
        <AuthorModal record={this.state.record} visible={this.state.modalVisible} setModalVisible={(flag) => this._setModalVisible(flag)}
          addAuthor={(fieldsValue) => this._addAuthor(fieldsValue)} loading={this.props.loading}
        />
      </PageHeaderLayout>
    );
  }
}
